package com.example.demo.entity.thread;

import java.util.concurrent.locks.StampedLock;

/**
 * @Author: zcb
 * @Description:
 * @Date: 2021/10/22
 */
public class StampLock {
    private final StampedLock stampedLock = new StampedLock();
    private double x;
    private double y;

    public void move(double deltaX, double deltaY) {
        //获取写锁
        long stamp = stampedLock.writeLock();
        try {
            this.x += deltaX;
            this.y += deltaY;
        } finally {
            //释放写锁
            stampedLock.unlock(stamp);
        }
    }

    public double distance() {
        //获取乐观读锁
        long stamp = stampedLock.tryOptimisticRead();
        double doubleX = this.x;
        double doubleY = this.y;
        //数据有改动
        if (!stampedLock.validate(stamp)) {
            //获取悲观读锁
            stamp = stampedLock.readLock();
            try {
                doubleX = this.x;
                doubleY = this.y;
            } finally {
                //释放悲观读锁
                stampedLock.unlock(stamp);
            }
        }
        return Math.sqrt(doubleX * doubleX + doubleY * doubleY);
    }
}
